﻿using Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace SFJDManagement
{
    /// <summary>
    /// Win_Account.xaml 的交互逻辑
    /// </summary>
    public partial class Win_Account : Window
    {
        Window win_Parent;
        public static List<ClassBrigade> list_Brigade = Runtime.xmlBrigade.GetAll();
        public static List<ClassConfig> list_User = Runtime.xmlUsers.GetAllUsers();
        public UC_StatisticsPanel statisticsDataGrid;
        public UC_MultiComboBox multiComboBox;
        public UC_MultiDateChoice multiDateChoice;

        public Win_Account(Window window)
        {
            win_Parent = window;
            win_Parent.Visibility = Visibility.Hidden;
            Visibility = Visibility.Visible;
            InitializeComponent();
            Ini();
            AddHeader();
            AddFooter();
        }

        /// <summary>
        /// 添加上边栏
        /// </summary>
        private void AddHeader()
        {
            //Button but_Print = GetButton("打印");
            //but_Print.Click += But_Print_Click;
            //layout_Header.Children.Add(but_Print);
            Button but_PrintPreview = GetButton("打印预览");
            but_PrintPreview.Click += But_PrintPreview_Click;
            layout_Header.Children.Add(but_PrintPreview);
            Button but_Print1 = GetButton("报账表格");
            but_Print1.Click += But_Print1_Click;
            layout_Header.Children.Add(but_Print1);
            Button but_Print2 = GetButton("回执单");
            but_Print2.Click += But_Print2_Click;
            layout_Header.Children.Add(but_Print2);
            ToggleButton toggle_Statistics = new ToggleButton()
            {
                Content = "统计", Padding = new Thickness(10,2,10,2),
                Margin = new Thickness(10, 5, 10, 5)
            };
            toggle_Statistics.Click += Toggle_Statistics_Click;
            layout_Header.Children.Add(toggle_Statistics);
            multiDateChoice = new UC_MultiDateChoice(layout_Data);
            multiDateChoice.TimeChanged += MultiDateChoice_TimeChanged;
            layout_Header.Children.Add(multiDateChoice);
        }

        private void But_Print2_Click(object sender, RoutedEventArgs e)
        {
            string html = new HtmlPrint2("回执单", layout_Data).GetHtml();
            System.IO.File.WriteAllText(Runtime.pathTemp + "\\SFJD\\Print2.html", html);
            System.Diagnostics.Process.Start(Runtime.pathTemp + "\\SFJD\\Print2.html");
        }

        private void But_Print1_Click(object sender, RoutedEventArgs e)
        {
            string html = new HtmlPrint1("莲湖大队", layout_Data).GetHtml();
            System.IO.File.WriteAllText(Runtime.pathTemp + "\\SFJD\\Print1.html", html);
            System.Diagnostics.Process.Start(Runtime.pathTemp + "\\SFJD\\Print1.html");
        }

        /// <summary>
        /// 日期选择发生变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MultiDateChoice_TimeChanged(object sender, EventArgs e)
        {
            DataFilter();
        }

        /// <summary>
        /// 统计开关
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Toggle_Statistics_Click(object sender, RoutedEventArgs e)
        {
            if((bool)(sender as ToggleButton).IsChecked)
            {
                ShowLeft();
                layout_Statistics.Visibility = Visibility.Visible;
                multiComboBox.Visibility = Visibility.Visible;
            }
            else
            {
                layout_Statistics.Visibility = Visibility.Collapsed;
                multiComboBox.Visibility = Visibility.Collapsed;
                for (int i = 0; i < layout_Data.Items.Count; i++)
                {
                    layout_Data.GetRow(i).Visibility = Visibility.Visible;
                }
            }
        }

        /// <summary>
        /// 显示左侧栏
        /// </summary>
        private void ShowLeft()
        {
            layout_Statistics.Children.Clear();
            statisticsDataGrid = new UC_StatisticsPanel(layout_Data);
            layout_Statistics.Children.Add(statisticsDataGrid);
            int index;
            if ((index = layout_Header.Children.IndexOf(multiComboBox)) < 0)
            {
                multiComboBox = new UC_MultiComboBox(statisticsDataGrid);
                multiComboBox.CheckedChange += MultiComboBox_CheckedChange;
                layout_Header.Children.Add(multiComboBox);
            }
            else
            {
                multiComboBox.Reflesh(statisticsDataGrid);
            }
        }

        /// <summary>
        /// 组合选择按钮改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MultiComboBox_CheckedChange(object sender, EventArgs e)
        {
            DataFilter();
        }

        /// <summary>
        /// 按照选择的条件对layout_Data进行筛选
        /// </summary>
        private void DataFilter()
        {
            //UIElementCollection uIElementCollection = (multiComboBox.Content as StackPanel).Children;

            for (int i = 0; i < layout_Data.Items.Count; i++)
            {
                layout_Data.GetRow(i).Visibility = Visibility.Visible;
            }
            if(multiComboBox != null)//筛选数据
            {
                foreach (StackPanel panel in (multiComboBox.Content as StackPanel).Children)
                {
                    ComboBox comboBox = panel.Children[1] as ComboBox;
                    if (comboBox.SelectedItem.ToString() == "---全 部---")
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 0; i < layout_Data.Columns.Count; i++)
                        {
                            if (layout_Data.Columns[i].Header.ToString() == comboBox.Name)
                            {
                                for (int j = layout_Data.Items.Count - 1; j >= 0; j--)
                                {
                                    DataGridRow row = layout_Data.GetRow(j);
                                    if (row.Visibility == Visibility.Collapsed)
                                        continue;
                                    if ((layout_Data.GetCell(j, i).Content as TextBlock).Text == comboBox.SelectedItem.ToString())
                                    {
                                        row.Visibility = Visibility.Visible;
                                        Console.Out.WriteLine("visible");
                                    }
                                    else
                                    {
                                        row.Visibility = Visibility.Collapsed;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            if (multiDateChoice.timeStart != DateTime.MinValue | multiDateChoice.timeEnd != DateTime.MaxValue)//筛选时间
            {
                DateTime timeCell = DateTime.MinValue;
                for (int i = 0; i < layout_Data.Columns.Count; i++)
                {
                    if (layout_Data.Columns[i].Header.ToString() == multiDateChoice.choiced)
                    {
                        for (int j = 0; j < layout_Data.Items.Count; j++)
                        {
                            DataGridRow row = layout_Data.GetRow(j);
                            if (row.Visibility == Visibility.Collapsed)
                                continue;
                            timeCell = DateTime.Parse((layout_Data.GetCell(j, i).Content as TextBlock).Text);
                            if (DateTime.Compare(timeCell,multiDateChoice.timeStart) < 0 | DateTime.Compare(timeCell, multiDateChoice.timeEnd) > 0)
                            {
                                row.Visibility = Visibility.Collapsed;
                            }
                        }
                        break;
                    }
                }
            }
            RowVisiblityChanged();
        }

        private void RowVisiblityChanged()
        {
            int index = 1;
            for(int i = 0; i < layout_Data.Items.Count; i++)
            {
                DataGridRow row = layout_Data.GetRow(i);
                if(row.Visibility == Visibility.Visible)
                {
                    row.Header = index;
                    index++;
                }
            }
        }

        /// <summary>
        /// 添加下边栏
        /// </summary>
        private void AddFooter()
        {
            layout_Footer.HorizontalAlignment = HorizontalAlignment.Center;
            UC_MultiToggle multiToggle = new UC_MultiToggle(layout_Data);
            multiToggle.ButtonFontSize = 20;
            multiToggle.ButtonMargin = new Thickness(5, 10, 5, 10);
            multiToggle.ButtonPadding = new Thickness(20, 5, 20, 5);
            multiToggle.CheckedChange += MultiToggle_CheckedChange;
            layout_Footer.Children.Add(multiToggle);
        }

        /// <summary>
        /// 切换按钮组的状态改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MultiToggle_CheckedChange(object sender, EventArgs e)
        {
            ToggleButton toggle = sender as ToggleButton;
            foreach(DataGridColumn column in layout_Data.Columns)
            {
                if(column.Header.ToString() == toggle.Content.ToString())
                {
                    column.Visibility = ((bool)toggle.IsChecked) ? Visibility.Visible : Visibility.Hidden;
                    break;
                }
            }
            if(statisticsDataGrid != null && statisticsDataGrid.Visibility == Visibility.Visible)
            {
                statisticsDataGrid.ChangeVisible(toggle.Content.ToString());
                multiComboBox.ChangeVisible(toggle.Content.ToString());
            }
        }

        private void But_PrintPreview_Click(object sender, RoutedEventArgs e)
        {
            string html = ExportDatatableToHtml(layout_Data);
            System.IO.File.WriteAllText(Runtime.pathTemp + "\\SFJD\\Acc.html", html);
            System.Diagnostics.Process.Start(Runtime.pathTemp + "\\SFJD\\Acc.html");
        }

        private void But_Print_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog dialog = new PrintDialog();
            if (dialog.ShowDialog() == true)
            {
                dialog.PrintVisual(layout_Data, "打印数据");
            }
        }

        /// <summary>
        /// 将DataTable直接打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawString(layout_Data.DataContext.ToString(), new Font(new System.Drawing.FontFamily("黑体"), 11), System.Drawing.Brushes.Black, 10, 35);
        }

        /// <summary>
        /// 生成一个标准按钮
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        Button GetButton(string content)
        {
            Button button = new Button();
            button.MinWidth = 50;
            button.Height = 50;
            button.Content = content;
            button.Margin = new Thickness(10, 5, 10, 5);
            return button;
        }

        /// <summary>
        /// 初始化DataGrid
        /// </summary>
        private void Ini()
        {
            layout_Data.EnableColumnVirtualization = false;//关闭虚拟化
            layout_Data.EnableRowVirtualization = false;
            layout_Data.ItemsSource = Runtime.xmlData.GetAllData();
            layout_Data.AutoGenerateColumns = false;
            layout_Data.CanUserAddRows = false;
            layout_Data.IsReadOnly = true;
            layout_Data.VerticalContentAlignment = VerticalAlignment.Center;
            layout_Data.Loaded += Layout_Data_Loaded;
            layout_Data.LoadingRow += DataGrid_LoadingRow;
            //定义各列
            DataGridTextColumn column_ID = new DataGridTextColumn()
            {
                Header = "字号",
                Binding = new Binding("ID")
            };
            layout_Data.Columns.Add(column_ID);
            DataGridTextColumn column_Brigade = new DataGridTextColumn()
            {
                Header = "委托人",
                Binding = new Binding("Brigade") { Converter = new ConverterBrigade() }
            };
            layout_Data.Columns.Add(column_Brigade);
            DataGridTextColumn column_Contact = new DataGridTextColumn()
            {
                Header = "联系人",
                Binding = new Binding("Contact")
            };
            layout_Data.Columns.Add(column_Contact);
            DataGridTextColumn column_CaseType = new DataGridTextColumn()
            {
                Header = "案件类型",
                Binding = new Binding("CaseType") { Converter = new ConverterCaseType() }
            };
            layout_Data.Columns.Add(column_CaseType);
            DataGridTextColumn column_User = new DataGridTextColumn()
            {
                Header = "完稿",
                Binding = new Binding("User") { Converter = new ConverterUser() }
            };
            layout_Data.Columns.Add(column_User);
            DataGridTextColumn column_Happen = new DataGridTextColumn()
            {
                Header = "事故时间",
                Binding = new Binding("TimeHappen") { StringFormat = "yy-MM-dd HH:mm" }
            };
            layout_Data.Columns.Add(column_Happen);
            DataGridTextColumn column_Entrust = new DataGridTextColumn()
            {
                Header = "委托时间",
                Binding = new Binding("TimeEntrust") { StringFormat = "yy-MM-dd" }
            };
            layout_Data.Columns.Add(column_Entrust);
            DataGridTextColumn column_Arrange = new DataGridTextColumn()
            {
                Header = "完稿时间",
                Binding = new Binding("TimeArrange") { StringFormat = "yy-MM-dd HH:mm:ss" }
            };
            layout_Data.Columns.Add(column_Arrange);
            DataGridTextColumn column_Vehicle = new DataGridTextColumn()
            {
                Header = "车辆及项目",
                Binding = new Binding("Vehicles") { Converter = new ConverterVehicle(), UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged}
            };
            layout_Data.Columns.Add(column_Vehicle);
            //生成多选框
            //CheckBox checkBox = new CheckBox() { };
        }

        //添加列显示状态按钮
        private void Layout_Data_Loaded(object sender, RoutedEventArgs e)
        {
            //添加序号
            DataGrid dataGrid = sender as DataGrid;
            dataGrid.LoadingRow += DataGrid_LoadingRow;
            dataGrid.UnloadingRow += DataGrid_UnloadingRow;
        }

        /// <summary>
        /// 添加行序号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            //添加序号
            DataGrid dataGrid = sender as DataGrid;
            dataGrid.LoadingRow += DataGrid_LoadingRow;
            dataGrid.UnloadingRow += DataGrid_UnloadingRow;
        }

        private void DataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;
            if (dataGrid.Items != null)
            {
                for (int i = 0; i < dataGrid.Items.Count; i++)
                {
                    try
                    {
                        DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
                        if (row != null)
                        {
                            row.Header = (i + 1).ToString();
                        }
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// 添加行序号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        /// <summary>
        /// 将DataTable转换为Html
        /// </summary>
        /// <param name="dg"></param>
        /// <returns></returns>
        protected string ExportDatatableToHtml(DataGrid dg)
        {
            return new HtmlGenerator(dg).GetHtml();
        }

        /// <summary>
        /// Brigade转换器
        /// </summary>
        public class ConverterBrigade : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string b = "ERRO";
                foreach (ClassBrigade brigade in list_Brigade)
                {
                    if (brigade.Guid.ToString() == value.ToString())
                    {
                        if(brigade.Brigade[brigade.Brigade.Count() - 1] != '队')
                        {
                            b = brigade.Brigade;
                        }
                        else
                        {
                            b = brigade.City + brigade.Brigade;
                        }
                        break;
                    }
                }
                return b;
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string b = Guid.Empty.ToString();
                foreach (ClassBrigade brigade in list_Brigade)
                {
                    if (brigade.FullName == value.ToString())
                    {
                        b = brigade.Guid.ToString();
                        break;
                    }
                }
                return b;
            }
        }

        /// <summary>
        /// User转换器
        /// </summary>
        public class ConverterUser : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string b = "ERRO";
                foreach (ClassConfig user in list_User)
                {
                    if (user.UserGuid.ToString() == value.ToString())
                    {
                        b = user.UserName;
                        break;
                    }
                }
                return b;
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string b = Guid.Empty.ToString();
                foreach (ClassConfig user in list_User)
                {
                    if (user.UserName == value.ToString())
                    {
                        b = user.UserGuid.ToString();
                        break;
                    }
                }
                return b;
            }
        }

        /// <summary>
        /// CaseType转换器
        /// </summary>
        public class ConverterCaseType : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return ((EnumCaseType)(int.Parse(value.ToString()))).ToString();
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return Enum.Parse(typeof(EnumCaseType), value.ToString());
            }
        }

        /// <summary>
        /// Vehicle转换器
        /// </summary>
        public class ConverterVehicle : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                string b = "";
                List<ClassVehicle> list = value as List<ClassVehicle>;
                foreach (ClassVehicle vehicle in list)
                {
                    if(Regex.IsMatch(vehicle.Number, "无"))
                    {
                        b += "无号牌" + vehicle.Type + "：";
                    }
                    else
                    {
                        b += vehicle.Number + "：";
                    }
                    if (vehicle.Procj) { b += "车检、"; }
                    if (vehicle.Procs) { b += "车速、"; }
                    if (vehicle.Prohj) { b += "痕迹、"; }
                    if (vehicle.Procy) { b += "成因、"; }
                    if (vehicle.Progc) { b += "过程、"; }
                    if (vehicle.Profx) { b += "方向、"; }
                    if (vehicle.Projsy) { b += "驾驶员、"; }
                    if (vehicle.Pross) { b += "车损、"; }
                    if (vehicle.Prosx) { b += "属性、"; }
                    b = b.Substring(0, b.Length - 1);
                    b += "\r\n";
                }
                b = b.Substring(0, b.Length - 2);
                return b;
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            win_Parent.Visibility = Visibility.Visible;
        }
    }
}
